<?php
namespace Home\Controller;
use Home\Controller\HomeController;

class CartController extends HomeController{

    public function _initialize()
    {
        parent::_initialize();
    }

    //购物车页面
    public function index(){
        //购物车商品
        $where['user_id'] = session('user_id');
        
        $cart = M('cart')->where($where)->order('store_id')->select();
        //把同一个店铺的商品放在一个数组里
        $arr = array();
        foreach($cart as $k=>$v){
            $arr[$v['store_id']][] = $v;
        }
        $this->assign('cart',$arr);

        //选项卡商品
        $where['goods_sale'] = 1;
        $where['goods_state'] = 1;
        $wxdgoods = M('goods')->where($where)->limit(10)->select();
        $this->assign('wxdgoods',$wxdgoods);

        $this->display();
    }

    //ajax 加减数量
    public function jiajian(){
        $post = I('post.');
        $data['goods_num'] = $post['num'];
        $where['goods_id'] = $post['goods_id'];

        $wxdgoods = M('goods')->where(array('goods_id'=>$where['goods_id']))->field('goods_stock')->find();//获得商品库存

        if($data['goods_num'] > $wxdgoods['goods_stock']){
            $this->ajaxReturn(array('p'=>false,'s'=>'商品已被您抢购一空'));
        }
        $where['user_id'] = session('user_id');
        $re = M('cart')->where($where)->save($data);
        if($re){
            $cart = M('cart')->where($where)->field('goods_price,goods_num')->find();
            //购买商品数量等于库存则改变状态不再点击
            $this->ajaxReturn(array('p'=>true,'m'=>$cart['goods_price']*$cart['goods_num']));
        }else{
            $this->ajaxReturn(array('p'=>false,'s'=>"数量增加失败，请稍后重试"));
        }

    }

    //ajax 删除单个商品
    public function del(){
        $where['goods_id'] = I('goods_id');
        $where['user_id'] = session("user_id");
        $re = M('cart')->where($where)->delete();
        if($re) {
            $a['n'] = M('cart')->where(array('user_id' => $where['user_id']))->count();
        }else{
            $a['n'] = false;
        }

        $this->ajaxReturn($a);
    }

    //ajax 清空购物车
    public function q_del(){
        $where['buyer_id'] = session("user_id");
        $re = M('cart')->where($where)->delete();
        if($re){
            $this->ajaxReturn(true);
        }else{
            $this->ajaxReturn(false);
        }
    }

}